package forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/*
分支合并框架演示
 */
class MyTask extends RecursiveTask<Integer>{

//  拆分后差值不能大于10
  private static final Integer value = 10;
//  拆分开始值
  private int begin;
//  拆分结束值
  private int end;
//  结果
  private int result;

//  创建有参构造
  public MyTask(int begin,int end){
    this.begin = begin;
    this.end = end;
  }

  @Override
  protected Integer compute() {
//    判断，若两数之差小于10，相加
    if((end - begin) <= value){
//      相加
      for (int i = begin; i <= end; i++) {
        result = result + i;
      }
    }else {//进一步拆分
//      获取中间值
      int middle = (begin + end)/2;
//      拆分左边
      MyTask myTask1 = new MyTask(begin,middle);
//      拆分右边
      MyTask myTask2 = new MyTask(middle+1, end);
//      调用方法拆分
      myTask1.fork();
      myTask2.fork();
//      合并
      result = myTask1.join() + myTask2.join();
    }

    return result;
  }
}

public class ForkJoinDemo {

  public static void main(String[] args) {

//    创建MyTask对象
    MyTask myTask = new MyTask(1, 100);
//    创建分支合并池对象
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
//    获取最终合并的结果
    try {
      Integer result = forkJoinTask.get();
      System.out.println(result);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
//    关闭池对象
    forkJoinPool.shutdown();


  }
}
